<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 背景卡片 -->
    <el-card>
      <!-- 搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="params.query" clearable @clear="getUserDate">
            <el-button slot="append" icon="el-icon-search" @click="getUserDate"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="this.userList" stripe border>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatusChage(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="174px">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editInfo(scope.row.id)"
            ></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserInfo(scope.row.id)"></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配权限"
              placement="top"
              :enterable="false"
            >
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pagenum"
        :page-sizes="[1, 3, 5,10]"
        :page-size="params.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <!-- 添加用户提示框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitFrom">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑用户信息 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="ediDialogClosed"
    >
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitEditFrom">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证手机号的规则
    var checkMobile = (rule, value, cb) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    var checkEmail = (rule, value, cb) => {
      const regMobile = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regMobile.test(value)) {
        return cb()
      }
      cb(new Error('请输入正确的邮箱'))
    }
    return {
      userList: [],
      total: 0,
      // pageNum: 0,
      params: {
        query: '',
        pagenum: 1,
        pagesize: 10
      },
      // 提示框
      addDialogVisible: false,
      // 修改用户信息提示框
      editDialogVisible: false,
      // 表单数据
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
          // { min: 6, max: 18, message: '长度在 6 到 18 个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
          // { min: 11, max: 11, message: '长度为11位手机号', trigger: 'blur' }
        ]
      },
      // 修改用户信息表单数据
      editForm: {},
      // 修改用户信息表单说数据验证规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getUserDate()
  },
  methods: {
    //   获取用户信息
    async getUserDate() {
      const { data: relust } = await this.$http.get('users', {
        params: this.params
      })
      if (relust.meta.status !== 200) {
        return this.$message.error(relust.meta.msg)
      }
      this.userList = relust.data.users
      this.total = relust.data.total
      // this.pageNum = Math.ceil(this.total / this.params.pagesize)
    },
    // 每页显示多少条数据
    handleSizeChange(newPagesize) {
      this.params.pagesize = newPagesize
      this.getUserDate()
    },
    // 当前页面发生改变是
    handleCurrentChange(newPageNum) {
      this.params.pagenum = newPageNum
      this.getUserDate()
    },
    // 改变用户状态
    async userStatusChage(userStatus) {
      console.log(userStatus)
      const { data: relust } = await this.$http.put(`users/${userStatus.id}/state/${userStatus.mg_state}`)
      // console.log(relust)
      if (relust.meta.status !== 200) {
        userStatus.mg_state = !userStatus.mg_state
        return this.$message.error('更新状态失败')
      }
      this.$message.success('更新状态成功')
    },
    // 重置数据
    addDialogClosed() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()
    },
    // 提交数据
    submitFrom() {
      this.$refs.addFormRef.validate(async (validate) => {
        if (!validate) return
        const { data: relust } = await this.$http.post('users', this.addForm)
        console.log(relust)
        if (relust.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        }
        this.$message.success('添加成功')
        this.addDialogVisible = false
        // this.$refs.addFormRef.resetFields()
        this.getUserDate()
      })
    },
    // 编辑用户信息
    async editInfo(id) {
      console.log(id)
      this.editDialogVisible = true
      // 根据用户ID查询用户信息
      const { data: relust } = await this.$http.get('users/' + id)
      if (relust.meta.status !== 200) {
        return this.$message.error('获取用户信息失败')
      }
      this.editForm = relust.data
    },
    // 重置修改信息
    ediDialogClosed() {
      this.editDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    // 提交修改之后的收据
    submitEditFrom() {
      // 这个方法是效验数据格式是否正确
      // this.$refs.editFormRef.validate(async (validate) => {})
      this.$refs.editFormRef.validate(async (validate) => {
        console.log(validate)
        if (!validate) return
        const { data: relust } = await this.$http.put('users/' + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          })
        // console.log(relust)
        if (relust.meta.status !== 200) {
          return this.$message.error('修改失败')
        }
        this.editDialogVisible = false
        this.getUserDate()
        this.$message.success('更新成功')
      })
    },
    // 删除用户信息
    async removeUserInfo(id) {
      const relust = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (relust !== 'confirm') {
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败')
      }
      this.$message.success('删除成功')
      this.getUserDate()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
